package ejb;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import dto.ElectionDTO;
import dto.GovernorDTO;
import dto.VoteDTO;
import entitymanagers.ElectionManager;
import model.Citizen;
import model.Election;
import model.Governor;
import utils.AbstractBean;


@Stateless
@LocalBean
public class ElectionManagerBean extends AbstractBean<Election> implements ElectionManager {
	@EJB
	private TimeManager tm;
	@PersistenceContext
	private EntityManager em;
	@Resource
	private SessionContext context;
	
	public ElectionManagerBean() {
		super(Election.class);
	}

	@Override
	protected EntityManager getEntityManager() {
		return em;
	}

	@Override
	public ElectionDTO getVotes(VoteDTO votes) {
		return null;
	
		
	}
	
	
	
	@Override
	public void getNewGovernor(GovernorDTO governorDTO) {
		Governor foundGovernor = em.find(Governor.class, context.getCallerPrincipal().getName());
		
		Governor governor = new Governor();
		governor.setCitizen(em.find(Citizen.class, context.getCallerPrincipal().getName()));
		//governor.setCitizen(em.find(Citizen.class, context.getCallerPrincipal().getName()));
		
		if(foundGovernor != null){
			em.merge(governor);
		}
		else{
			em.persist(governor);
			tm.setGovernorElected(true);
			em.merge(governor.getCitizen());
			
		}
		
	}
	

}
